package com.example.xyr.myapplication.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.provider.MediaStore
import java.io.File
import java.io.FileInputStream


/**
 * Created by ylcf on 2018/8/22.
 */
class ImageUtils {
    companion object {
        //根据uri转file
        fun getStringPath(context: Context, uri: Uri): File {
            lateinit var path: String
            val proj = arrayOf<String>(MediaStore.Images.Media.DATA)
            val cursor = context.getContentResolver().query(uri, proj, null, null, null)
            if (cursor.moveToFirst()) {
                val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                path = cursor.getString(columnIndex)
            }
            cursor.close()
            return File(path)
        }

        //根据file转bitmap
        fun getBitmapByFile(file: File): Bitmap {
            var b: Bitmap? = null
            val IMAGE_MAX_SIZE = 600

            //Decode image size
            val o = BitmapFactory.Options()
            o.inJustDecodeBounds = true

            var fis = FileInputStream(file)
            BitmapFactory.decodeStream(fis, null, o)
            fis.close()

            var scale = 1
            if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
                scale = Math.pow(2.0, Math.round(Math.log(IMAGE_MAX_SIZE / Math.max(o.outHeight, o.outWidth) as Double) / Math.log(0.5)).toInt().toDouble()).toInt()
            }

            //Decode with inSampleSize
            val o2 = BitmapFactory.Options()
            o2.inSampleSize = scale
            fis = FileInputStream(file)
            b = BitmapFactory.decodeStream(fis, null, o2)
            fis.close()
            return b
        }
    }

}